package common;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.widget.EdgeEffectCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.mobstat.StatService;
import com.laoxinwen.app.R;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;

import util.MyAnimator;
import util.bitmap.FileUtil;
import util.bitmap.Img;
import util.bitmap.ImgPool;

public abstract class BaseActivity extends FragmentActivity implements View.OnClickListener {

    private static final int MIN_DISTANCE_FOR_FLING = 40; // dips
    private static final int MIN_FLING_VELOCITY = 400; // dips
    private VelocityTracker mVelocityTracker;
    private int mMinimumVelocity;
    private int mMaximumVelocity;
    private int mFlingDistance;
    private int mTouchSlop;
    private int mPointerId;
    private boolean mIsBeingDragged;

    private boolean blockTouchAndKeyEvent;
    private float fingerX;
    private float fingerY;
    private int ctheme;

    //
    //图片相关
    //
    protected File cacheDir = FileUtil.getFileDir();
    protected File fileDir = FileUtil.getCacheDir();
    protected HashMap<String, Img> imgMap = new HashMap<>();
    protected ImgPool imgPool = new ImgPool() {
        @Override
        public void bitmapDecoded(Img<?> img, View bindedView, boolean isFistDecode) {
            ImageView iv = (ImageView) bindedView;
            iv.setImageBitmap(img.getBitmap());
            if (isFistDecode) {
                MyAnimator.alphaListPic(bindedView);
            }
        }

        @Override
        public void bitmapNotDecoded(View bindedView) {
            ImageView iv = (ImageView) bindedView;
            iv.setImageResource(R.drawable.default_img_bg_large);
        }

        @Override
        public void bind(Img<?> img, View view) {
            if(UserConfig.isNoPic()) {
                return;
            }
            super.bind(img, view);
        }
    };

    protected Img getImg(String url) {
        Img img = imgMap.get(url);
        if (null == img) {
            img = new Img(cacheDir, fileDir, url);
            imgMap.put(url, img);
        }
        return img;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Window window = getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // Translucent status bar
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            window.addFlags(Window.FEATURE_NO_TITLE);
//             Translucent navigation bar
//            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setTheme(MyApp.getMyTheme().getThemeResId());
        ctheme = MyApp.getMyTheme().getId();

        final float density = getResources().getDisplayMetrics().density;
        final ViewConfiguration configuration = ViewConfiguration.get(this);
        mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
        mMinimumVelocity = (int) (MIN_FLING_VELOCITY * density);
        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
        mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);

        super.onCreate(savedInstanceState);
    }

    @Override
    public void onPause() {
        super.onPause();
        imgPool.releaseSomeMemory();
        if (mVelocityTracker != null) {
            mVelocityTracker.clear();
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
        //umeng统计
        MobclickAgent.onPause(this);
        //baidu统计
        StatService.onPause(this);
    }

    @Override
    protected void onResume() {
        if (ctheme != MyApp.getMyTheme().getId()) {
            this.restartSelf();
        }
        super.onResume();
        blockTouchAndKeyEvent = false;
        //umeng统计
        MobclickAgent.onResume(this);
        //baidu统计
        StatService.onResume(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        imgPool.shutdown();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 重启activity
     */
    protected void restartSelf() {
//        this.recreate();
        this.finish();
        Intent intent = this.getIntent();
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        this.startActivity(intent);
        overridePendingTransition(0, 0);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
        blockTouchAndKeyEvent = true;
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
        blockTouchAndKeyEvent = true;
    }

    //
    //根据id找view相关
    //
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface id {
        int value();
    }

    public void loadView() {
        Field[] fields = getClass().getDeclaredFields();
        try {
            for (Field field : fields) {
                if (field.isAnnotationPresent(BaseActivity.id.class)) {
                    field.setAccessible(true);
                    field.set(this, findViewById(field.getAnnotation(BaseActivity.id.class).value()));
                }
            }
        } catch (Exception e) {
            Log.e(BaseActivity.class.getName(), e.toString());
        }
    }

    /**
     * 调用 findViewById(id)
     *
     * @param id
     */
    public <T extends View> T f(int id) {
        return (T) findViewById(id);
    }

    /**
     * 调用 v.findViewById(id)
     *
     * @param id
     * @param v
     */
    public <T extends View> T f(int id, View v) {
        return (T) v.findViewById(id);
    }

    //
    //手势、按键相关
    //

    /**
     * 隐藏软键盘
     */
    public void hideInputKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        View v = getCurrentFocus();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 强制弹出软键盘
     *
     * @param view
     */
    public void showInputKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return blockTouchAndKeyEvent || super.dispatchKeyEvent(event);
    }

    protected void checkSlideGesture(MotionEvent ev) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(ev);

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPointerId = ev.getPointerId(0);
                fingerX = ev.getX();
                fingerY = ev.getY();
                mIsBeingDragged = false;
                break;
            case MotionEvent.ACTION_MOVE:
                final float diffX = Math.abs(ev.getX() - fingerX);
                final float diffY = Math.abs(ev.getY() - fingerY);
                if (diffX > mTouchSlop || diffY > mTouchSlop) {
                    mIsBeingDragged = true;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (mIsBeingDragged) {
                    final float deltaX = ev.getX() - fingerX;
                    final float deltaY = ev.getY() - fingerY;

                    mVelocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
                    float velocityX = mVelocityTracker.getXVelocity(mPointerId);
                    float velocityY = mVelocityTracker.getYVelocity(mPointerId);

                    if (Math.abs(deltaX) > Math.abs(deltaY)) {
                        if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocityX) > mMinimumVelocity) {
                            if (deltaX > 0) {
                                onRightSlide();
                            } else {
                                onLeftSlide();
                            }
                        }
                    } else {
                        if (Math.abs(deltaY) > mFlingDistance && Math.abs(velocityY) > mMinimumVelocity) {
                            if (deltaY > 0) {
                                onDownSlide();
                            } else {
                                onUpSlide();
                            }
                        }
                    }
                }
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (!blockTouchAndKeyEvent) {
            checkSlideGesture(ev);
        }

        return blockTouchAndKeyEvent || super.dispatchTouchEvent(ev);
    }

    protected void onRightSlide() {

    }

    protected void onLeftSlide() {

    }

    protected void onDownSlide() {

    }

    protected void onUpSlide() {

    }

    @Override
    public void onClick(View view) {

    }

    //
    //其他util
    //
    final public boolean em(String str) {
        return null == str || "".equals(str);
    }


    public MyApp getMyApplication() {
        return (MyApp) getApplication();
    }

    protected void showToast(Object obj) {
        Toast.makeText(this, String.valueOf(obj), Toast.LENGTH_SHORT).show();
    }

}
